package com.fred.taobao.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fred.taobao.domain.DaySellDomain;
import com.fred.taobao.util.SqlUtil;

public class DaySellDao {
	public List<DaySellDomain> getDaySellFromSql(String startDate,String endDate){
		SqlUtil sqlUtil=new SqlUtil();
		Calendar calStart = Calendar.getInstance();
		Calendar calEnd=Calendar.getInstance();
		SimpleDateFormat sdf=new SimpleDateFormat();
		sdf.applyPattern("yyyy-MM-dd");
		Date dateStartDate=null;
		Date dateEndDate=null;
		try{
			dateStartDate=sdf.parse(startDate);
			dateEndDate=sdf.parse(endDate);
		}catch(Exception e){
			e.printStackTrace();
		}
		Connection conn=sqlUtil.getConnection();
		PreparedStatement pre=null;
		ResultSet result=null;
		calEnd.setTime(dateEndDate);
		try{
			List<DaySellDomain> daysSell=new ArrayList<DaySellDomain>();
			calStart.setTime(dateStartDate);
			sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
			
			while(calStart.before(calEnd)){
				List<String> nicks=new ArrayList<String>();
				float totalFee=0;
				int totalNum=0;
				int orderNum=0;
				String dateStartStr=sdf.format(calStart.getTime());
				calStart.add(Calendar.DATE, 1);
				String next=sdf.format(calStart.getTime());
				pre=conn.prepareStatement("select * from sell_table where order_date>=? and order_date<=?");
				pre.setString(1, dateStartStr);
				pre.setString(2, next);
				result=pre.executeQuery();
				while(result.next()){
					totalFee+=result.getFloat("total_fee");
					totalNum+=result.getInt("order_number");
					nicks.add(result.getString("buyer_nick"));
					orderNum=result.getRow();
				}
				DaySellDomain daySellDomain=new DaySellDomain();
				daySellDomain.setBuyerNum(nicks.size());
				daySellDomain.setDate(dateStartStr.substring(0, 10));
				daySellDomain.setOrderNum(orderNum);
				daySellDomain.setOrderTotalFee(totalFee);
				daySellDomain.setOrderItemNum(totalNum);
				daySellDomain.setBuyerVer(nicks.size()==0?(0):(daySellDomain.getOrderTotalFee()/nicks.size()));
				daysSell.add(daySellDomain);
		
			}
			return daysSell;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			try{
				if(result!=null){
					result.close();
				}
				if(pre!=null){
					pre.close();
				}
				if(conn!=null){
					conn.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		
	}
}
